//
//  CZHomeViewController.swift
//  XLWB009
//
//  Created by apple on 3/19/16.
//  Copyright © 2016 apple. All rights reserved.
//

import UIKit

class CZHomeViewController: CZBaseTableViewController {

    //属性
    private let RequesIdentfier="RequesIdentfier"
    
    //微博数据
    var statuses:[CZStatus]?{
        didSet{
            self.tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //登陆以后才操作后面的
        if !CZUserAccoutModel.sharedInstance.userLogin{
        
            return
        }
        //设置导航栏
        setNavigationItem()
        setTitleButton()
        prepareTableView()
        
        //使用VM加载数据
        CZStatusModel.sharedInstance.loadStatus { (statuses, error) -> () in
            if error != nil{
                
                print("加载微博数据出错了：\(error)")
                return
                
            }
             //当获取数据后，将数据赋值给控制器的属性，让tableView根据statuses来显示cell
            self.statuses=statuses
        }
        
        //暴力测试
        let urlString="https://api.weibo.com/2/statuses/home_timeline.json"
        let parameters=["access_token":CZUserAccoutModel.sharedInstance.userAccount!.access_token!]
        CZNxetWorkTool.sharedInstance.afnManager.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            
            print("result\(result)")
            
            }) { (_, error) -> Void in
                
                print("error\(error)")
        }
    }

    //注册cell
    private func prepareTableView(){
    
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: RequesIdentfier)
    
    }
    
    //设置导航栏
    func setTitleButton(){
//        let name=CZUserAccoutModel.sharedInstance.userAccount?.screen_name
        
        let titleLbale=CZHomeTileButton(title: "我的微博", imageName: "navigationbar_arrow_down")
        titleLbale.addTarget(self, action: "didClickTitleButton:", forControlEvents: UIControlEvents.TouchUpInside)
        
        navigationItem.titleView=titleLbale
    }
  
    //添加左右按钮
    func setNavigationItem(){
        let button=UIButton()
        
        button.setBackgroundImage(UIImage(named: "navigationbar_friendsearch"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "navigationbar_friendsearch_highlighted"), forState: UIControlState.Normal)
        button.sizeToFit()
        
        navigationItem.leftBarButtonItem=UIBarButtonItem(customView: button)
        
        let rigthButton=UIButton()
        rigthButton.setBackgroundImage(UIImage(named: "navigationbar_pop"), forState: UIControlState.Normal)
        rigthButton.setBackgroundImage(UIImage(named: "navigationbar_pop_highlighted"), forState: UIControlState.Normal)
        rigthButton.sizeToFit()
        
        navigationItem.rightBarButtonItem=UIBarButtonItem(customView: rigthButton)
    }

    //点击事件
   @objc private func didClickTitleButton(button:CZHomeTileButton){
        //当点击按钮的时候selected取反
        button.selected = !button.selected
    
    //·······报错····
//        UIView.animateWithDuration(CZDefaultDuration) { () -> Void in
//            button.imageView?.transform = button.selected ? CGAffineTransformMakeScale(<#T##sx: CGFloat##CGFloat#>, <#T##sy: CGFloat##CGFloat#>)
//        }
    UIView.animateWithDuration(CZDefaultDuration) { () -> Void in
        button.imageView?.transform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.001)) : CGAffineTransformIdentity
    }
        if button.selected{
        
            let popoerVC=CZPopoerViewController()
            
            //设置model的样式
            popoerVC.modalPresentationStyle = .Popover
            
            //设置代理
            popoerVC.popoverPresentationController?.delegate = self
            
            //popoer箭头指向sourceView，默认指向左上角
            popoerVC.popoverPresentationController?.sourceView=navigationItem.titleView
            
            //把bounds给sourceRect
            popoerVC.popoverPresentationController?.sourceRect=(navigationItem.titleView?.bounds)!
            
            //设置poposer显示的大小
            popoerVC.preferredContentSize=CGSize(width: 200, height:44*popoerVC.titles.count)
            
            //弹出
            presentViewController(popoerVC, animated:true, completion: nil)
        }
    }
}

//将tableview相关的都写到这里面
extension CZHomeViewController{
    //返回多少cell
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
            return statuses?.count ?? 0
        }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell=tableView.dequeueReusableCellWithIdentifier(RequesIdentfier, forIndexPath: indexPath)
        
        //设置cell内容
        cell.textLabel?.text=statuses?[indexPath.row].text
        
        return cell
    }
}

extension CZHomeViewController : UIPopoverPresentationControllerDelegate{
    //不让popoer适配，默认适配
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        
        return UIModalPresentationStyle.None
    }
    
    func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool {
        
        let titleButton=navigationItem.titleView as! CZHomeTileButton
        
       didClickTitleButton(titleButton)
        
        return true
    }
}